import React, { Component } from "react";
import { message, Tree, Spin } from "antd";
import expenseTypeService from "containers/setting/expense-type/expense-type.service";
import { connect } from "react-redux";

const { TreeNode } = Tree;

class ExpenseAdditional extends Component {
  // 可作为费用类别详情组件扩展
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      autoExpandParent: true,
      applicationTypes: [],
      expandedKeys: [],
      defaultCheckedKeys: [],
    };
  }

  componentDidMount() {
    this.updateKeys(this.props);
  }

  componentDidUpdate(prevProps) {
    if (prevProps.nowWidget.fieldOID !== this.props.nowWidget.fieldOID) {
      this.updateKeys(this.props);
    }
  }

  updateKeys = (props) => {
    const { expenseTypeSetOfBooks, nowWidget } = props;
    let { defaultCheckedKeys } = this.state;
    this.setState({ loading: true });
    expenseTypeService
      .getApplicationList(expenseTypeSetOfBooks.id)
      .then((res) => {
        const { trees, expandedKeys } = res;
        defaultCheckedKeys = [];
        if (
          !nowWidget.config ||
          !nowWidget.config.applicationScopMap ||
          !nowWidget.config.applicationScopMap[0]
        ) {
          // 兼容老数据，如果没有config则全选
          trees.map((item) => {
            defaultCheckedKeys.push(item.key);
          });
        } else {
          nowWidget.config
            ? nowWidget.config.applicationScopMap &&
              nowWidget.config.applicationScopMap.map((item) => {
                if (item.scope === "all") {
                  defaultCheckedKeys.push(item.dimensionId);
                } else {
                  defaultCheckedKeys.push(...item["formIds"]);
                }
              })
            : (defaultCheckedKeys = []);
        }
        this.setState({
          applicationTypes: trees,
          defaultCheckedKeys,
          expandedKeys,
          loading: false,
        });
      })
      .catch((e) => {
        this.setState({ loading: false });

        if (e.response) {
          message.error(e.response.data.message);
        } else {
          message.error(e.message);
        }
      });
  };

  renderTreeNodes = (data) => {
    const { disabled } = this.props;
    return data.map((item) => {
      item.disabled = disabled || item.disabled;
      if (item.children && item.children[0]) {
        return (
          <TreeNode
            key={item.key}
            title={item.title}
            dataRef={item}
            disabled={item.disabled}
            selectable={item.selectable}
          >
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} />;
    });
  };

  onCheck = (checkedKeys) => {
    let { applicationTypes } = this.state;
    let applicationScopMap = [],
      defaultCheckedKeys = [];
    applicationTypes.forEach((kids) => {
      kids.children.map((child) => {
        let childScope = {};
        const isCheckedAll = !!~checkedKeys.indexOf(child.key);
        const filterAll = child.children.filter(
          (item) => item.disabled === false
        );
        childScope["dimensionId"] = child.key;
        childScope["formIds"] = [];
        if (isCheckedAll) {
          childScope["scope"] = "all";
        } else {
          childScope["scope"] = "custom";
          child.children.map((item) => {
            if (!!~checkedKeys.indexOf(item.key)) {
              childScope["formIds"].push(item.key);
            }
          });
          if (childScope["formIds"].length === filterAll.length) {
            // 如果非禁用都被选中则默认全选
            childScope["scope"] = "all";
          }
        }
        applicationScopMap.push(childScope);
      });
    });
    applicationScopMap.map((item) => {
      if (item.scope === "all") {
        defaultCheckedKeys.push(item.dimensionId);
      } else {
        defaultCheckedKeys.push(...item["formIds"]);
      }
    });
    this.setState({ defaultCheckedKeys });
    this.props.onChange(applicationScopMap);
  };

  onExpand = (expandedKeys) => {
    this.setState({ expandedKeys });
  };

  renderAdditional = () => {
    const { nowWidget, title } = this.props;
    const {
      autoExpandParent,
      applicationTypes,
      expandedKeys,
      defaultCheckedKeys,
      loading,
    } = this.state;
    let additionalElement = "";
    if (nowWidget.fieldType === "ASSOCIATE_APPLICATION") {
      additionalElement = loading ? (
        <div style={{ minHeight: 400 }}>
          <Spin></Spin>
        </div>
      ) : (
        <Tree
          checkable
          onCheck={this.onCheck}
          onExpand={this.onExpand}
          checkedKeys={defaultCheckedKeys}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
        >
          {this.renderTreeNodes(applicationTypes)}
        </Tree>
      );
    }
    return (
      <section>
        {title && <div className="widget-setting-title">{title}</div>}
        <div>{additionalElement}</div>
      </section>
    );
  };

  render() {
    return this.renderAdditional();
  }
}

ExpenseAdditional.propTypes = {
  nowWidget: React.PropTypes.object,
  onChange: React.PropTypes.func,
  title: React.PropTypes.string,
  nowSelectedIndex: React.PropTypes.number,
  disabled: React.PropTypes.bool,
};

function mapStateToProps(state) {
  return {
    expenseTypeSetOfBooks: state.setting.expenseTypeSetOfBooks,
  };
}

export default connect(mapStateToProps)(ExpenseAdditional);
